<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品类型" prop="productType">
        <el-select v-model="queryParams.productType" placeholder="商品类型" clearable size="small">
          <el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="商品状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['shop:product:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" row-key="productId" border>
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品类型" align="center" prop="productType">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.productType" />
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="销量" align="center" prop="sales" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-folder" @click="handleResource(scope.row)">课程资源</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品类型" prop="productType">
          <el-select v-model="form.productType" placeholder="请选择商品类型">
            <el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述" prop="productDesc">
          <el-input v-model="form.productDesc" type="textarea" placeholder="请输入商品描述" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="form.originalPrice" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImg">
          <image-upload v-model="form.coverImg" />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 课程资源对话框 -->
    <el-dialog :title="'课程资源 - ' + resourceTitle" :visible.sync="resourceOpen" width="800px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddResource">新增</el-button>
        </el-col>
      </el-row>

      <el-table :data="resourceList" border>
        <el-table-column label="资源标题" align="center" prop="title" />
        <el-table-column label="资源类型" align="center" prop="resourceType">
          <template slot-scope="scope">
            <dict-tag :options="resourceTypeOptions" :value="scope.row.resourceType" />
          </template>
        </el-table-column>
        <el-table-column label="时长" align="center" prop="duration">
          <template slot-scope="scope">
            <span>{{ formatDuration(scope.row.duration) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="播放" align="center" prop="status">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-play" @click="playVideo(scope.row)">播放</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit"
              @click="handleUpdateResource(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete"
              @click="handleDeleteResource(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改课程资源对话框 -->
      <el-dialog :title="resourceFormTitle" :visible.sync="resourceFormOpen" width="500px" append-to-body>
        <el-form ref="resourceForm" :model="resourceForm" :rules="resourceRules" label-width="80px">
          <el-form-item label="资源标题" prop="title">
            <el-input v-model="resourceForm.title" placeholder="请输入资源标题" />
          </el-form-item>
          <el-form-item label="资源类型" prop="resourceType">
            <el-select v-model="resourceForm.resourceType" placeholder="请选择资源类型" @change="handleResourceTypeChange">
              <el-option v-for="dict in resourceTypeOptions" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="资源地址" prop="url">
            <div v-if="resourceForm.resourceType === '1'">
              <el-upload class="upload-video" :show-file-list="false" :before-upload="handleBeforeUpload"
                :http-request="handleUpload">
                <el-button size="small" type="primary">选择视频文件</el-button>
              </el-upload>
              <el-progress v-if="uploadProgress > 0" :percentage="uploadProgress"
                :format="progressFormat"></el-progress>
              <div v-if="resourceForm.url" class="upload-url">
                已上传: {{ resourceForm.url }}
              </div>
            </div>
            <el-input v-else v-model="resourceForm.url" placeholder="请输入资源地址" />
          </el-form-item>
          <el-form-item label="时长(秒)" prop="duration">
            <el-input-number v-model="resourceForm.duration" :min="0" />
          </el-form-item>
          <el-form-item label="排序号" prop="sortOrder">
            <el-input-number v-model="resourceForm.sortOrder" :min="0" />
          </el-form-item>
          <!-- <el-form-item label="查看" prop="status">
            <el-button size="small" type="primary" @click="playVideo">播放视频</el-button>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitResourceForm">确 定</el-button>
          <el-button @click="cancelResource">取 消</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, listResource, addResource, updateResource, delResource } from "@/api/shop/product";
import OSS from 'ali-oss';

export default {
  name: "Product",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      productList: [],
      // 课程资源列表
      resourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示资源弹出层
      resourceOpen: false,
      // 是否显示资源表单弹出层
      resourceFormOpen: false,
      // 资源弹出层标题
      resourceTitle: "",
      // 资源表单弹出层标题
      resourceFormTitle: "",
      // 类型数据字典
      typeOptions: [
        {
          value: "1",
          label: "课程",
          listClass: "primary"
        },
        {
          value: "2",
          label: "电子书",
          listClass: "primary"

        },
        {
          value: "3",
          label: "音频",
          listClass: "primary"

        }
      ],
      // 资源类型数据字典
      resourceTypeOptions: [
        {
          value: "1",
          label: "视频",
          listClass: "primary"

        },
        {
          value: "2",
          label: "文档",
          listClass: "primary"

        },
        {
          value: "3",
          label: "音频",
          listClass: "primary"

        }
      ],
      // 状态数据字典
      statusOptions: [
        {
          value: "0",
          label: "正常",
          listClass: "primary"

        },
        {
          value: "1",
          label: "停用",
          listClass: "primary"

        }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        productType: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 资源表单参数
      resourceForm: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        productType: [
          { required: true, message: "商品类型不能为空", trigger: "change" }
        ],
        price: [
          { required: true, message: "商品价格不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "商品状态不能为空", trigger: "change" }
        ]
      },
      // 资源表单校验
      resourceRules: {
        title: [
          { required: true, message: "资源标题不能为空", trigger: "blur" }
        ],
        resourceType: [
          { required: true, message: "资源类型不能为空", trigger: "change" }
        ],
        url: [
          { required: true, message: "资源地址不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        const { rows, total } = response.data;
        this.productList = rows;
        this.total = total;
        this.loading = false;
      });
    },
    playVideo(row) {
      // 播放视频
      window.open(row.url, '_blank');
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: undefined,
        productName: undefined,
        productDesc: undefined,
        productType: undefined,
        price: undefined,
        originalPrice: undefined,
        coverImg: undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId;
      getProduct(productId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != undefined) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productId = row.productId;
      this.$modal.confirm('是否确认删除商品编号为"' + productId + '"的数据项？').then(function () {
        return delProduct(productId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 课程资源按钮操作 */
    handleResource(row) {
      this.resourceOpen = true;
      this.resourceTitle = row.productName;
      this.resourceForm.productId = row.productId;
      this.getResourceList(row.productId);
    },
    /** 查询课程资源列表 */
    getResourceList(productId) {
      listResource(productId).then(response => {
        this.resourceList = response.data;
      });
    },
    // 格式化时长
    formatDuration(seconds) {
      if (!seconds) return "0秒";
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const remainingSeconds = seconds % 60;
      let result = "";
      if (hours > 0) result += hours + "小时";
      if (minutes > 0) result += minutes + "分钟";
      if (remainingSeconds > 0) result += remainingSeconds + "秒";
      return result;
    },
    /** 新增课程资源 */
    handleAddResource() {
      this.resourceForm = {
        productId: this.resourceForm.productId,
        title: undefined,
        resourceType: undefined,
        url: undefined,
        duration: 0,
        sortOrder: 0,
        status: "0"
      };
      this.resourceFormOpen = true;
      this.resourceFormTitle = "添加课程资源";
    },
    /** 修改课程资源 */
    handleUpdateResource(row) {
      this.resourceForm = row;
      this.resourceFormOpen = true;
      this.resourceFormTitle = "修改课程资源";
    },
    /** 删除课程资源 */
    handleDeleteResource(row) {
      const resourceId = row.resourceId;
      this.$modal.confirm('是否确认删除该课程资源？').then(function () {
        return delResource(resourceId);
      }).then(() => {
        this.getResourceList(this.resourceForm.productId);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 取消课程资源
    cancelResource() {
      this.resourceFormOpen = false;
      this.resetForm("resourceForm");
    },
    /** 提交课程资源 */
    submitResourceForm() {
      this.$refs["resourceForm"].validate(valid => {
        if (valid) {
          if (this.resourceForm.resourceId != undefined) {
            updateResource(this.resourceForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.resourceFormOpen = false;
              this.getResourceList(this.resourceForm.productId);
            });
          } else {
            addResource(this.resourceForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.resourceFormOpen = false;
              this.getResourceList(this.resourceForm.productId);
            });
          }
        }
      });
    },
    // 资源类型改变
    handleResourceTypeChange(val) {
      this.resourceForm.url = '';
      this.uploadProgress = 0;
    },

    // 上传前校验
    handleBeforeUpload(file) {
      const isVideo = file.type.indexOf('video/') !== -1;
      const isLt2G = file.size / 1024 / 1024 / 1024 < 2;

      if (!isVideo) {
        this.$message.error('只能上传视频文件!');
        return false;
      }
      if (!isLt2G) {
        this.$message.error('视频大小不能超过 2GB!');
        return false;
      }
      return true;
    },

    // 处理文件上传
    async handleUpload({ file }) {
      try {
        // 创建视频元素获取时长
        const video = document.createElement('video');
        video.preload = 'metadata';
        
        video.onloadedmetadata = async () => {
          // 获取视频时长(秒)
          const duration = Math.round(video.duration);
          this.resourceForm.duration = duration;
          
          // 初始化OSS客户端
          this.client = new OSS({
            region: "oss-cn-guangzhou",
            accessKeyId: "LTAI5tKsHGypsVpazRgmbLRm",
            accessKeySecret: "YBeqokOdXpFh9Hk1Mdq9hBaob2JhUA",
            bucket: "fanxiao",
          });

          // 生成唯一文件名
          const fileName = '/knowage_pay_project/' + new Date().getTime() + '_' + file.name;

          // 分片上传
          const result = await this.client.multipartUpload(fileName, file, {
            progress: (p) => {
              this.uploadProgress = Math.floor(p * 100);
            },
            partSize: 1024 * 1024 * 10,
            parallel: 4,
          });
          
          const uploadedUrl = 'https://fanxiao.oss-cn-guangzhou.aliyuncs.com' + result.name;
          this.resourceForm.url = uploadedUrl;
          this.$message.success('上传成功');
        };
        
        video.src = URL.createObjectURL(file);
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error('上传失败，请重试');
      }
    },

    // 进度条格式化
    progressFormat(percentage) {
      return percentage === 100 ? '上传完成' : `${percentage}%`;
    },
  }
};
</script>

<style scoped>
.upload-video {
  margin-bottom: 10px;
}

.upload-url {
  margin-top: 10px;
  color: #666;
  word-break: break-all;
}
</style>